package main

import (
	"context"

	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"
	"time"

	"github.com/ghodss/yaml"
	"github.com/prometheus/client_golang/prometheus"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"github.com/ingopansa/userinfoservice/server"

	"github.com/ingopansa/userinfoservice/tokenprovider"
)

func commandServe() *cobra.Command {
	return &cobra.Command{
		Use:     "serve [ config file ]",
		Short:   "Connect to the defined userinfo data store and start serving requests",
		Long:    ``,
		Example: "userinfoservice serve config.yaml",
		Run: func(cmd *cobra.Command, args []string) {
			if err := serve(cmd, args); err != nil {
				fmt.Fprintln(os.Stderr, err)
				os.Exit(2)
			}
		},
	}
}

func serve(cmd *cobra.Command, args []string) error {
	switch len(args) {
	default:
		return errors.New("surplus arguments")
	case 0:
		return errors.New("no arguments provided")
	case 1:
	}

	configFile := args[0]
	configData, err := ioutil.ReadFile(configFile)
	if err != nil {
		return fmt.Errorf("failed to read config file %s: %v", configFile, err)
	}

	var c Config
	if err := yaml.Unmarshal(configData, &c); err != nil {
		return fmt.Errorf("error parse config file %s: %v", configFile, err)
	}

	logger, err := newLogger(c.Logger.Level, c.Logger.Format)
	if err != nil {
		return fmt.Errorf("invalid config: %v", err)
	}
	if c.Logger.Level != "" {
		logger.Infof("config using log level: %s", c.Logger.Level)
	}

	// Fast checks. Perform these first for a more responsive CLI.
	checks := []struct {
		bad    bool
		errMsg string
	}{
		{c.Issuer == "", "no issuer specified in config file"},
		{c.Storage.Config == nil, "no storage supplied in config file"},
		{c.HTTP.HTTP == "" && c.HTTP.HTTPS == "", "must supply a HTTP/HTTPS  address to listen on"},
		{c.HTTP.HTTPS != "" && c.HTTP.TLSCert == "", "no cert specified for HTTPS"},
		{c.HTTP.HTTPS != "" && c.HTTP.TLSKey == "", "no private key specified for HTTPS"},
	}

	for _, check := range checks {
		if check.bad {
			return fmt.Errorf("invalid config: %s", check.errMsg)
		}
	}

	logger.Infof("config issuer: %s", c.Issuer)

	prometheusRegistry := prometheus.NewRegistry()
	err = prometheusRegistry.Register(prometheus.NewGoCollector())
	if err != nil {
		return fmt.Errorf("failed to register Go runtime metrics: %v", err)
	}

	err = prometheusRegistry.Register(prometheus.NewProcessCollector(os.Getpid(), ""))
	if err != nil {
		return fmt.Errorf("failed to register process metrics: %v", err)
	}

	s, err := c.Storage.Config.Open(logger)
	if err != nil {
		return fmt.Errorf("failed to initialize storage: %v", err)
	}
	logger.Infof("config storage: %s", c.Storage.Type)

	//var tokenProviders []TokenProvider
	//for _, tp := range c.TokenProviders {
	//	tokenProviders = append(tokenProviders, tp)
	//	logger.Infof( "config tokenprovider: type=%s, ID=%s", tp.Type, tp.Id )
	//}

	var endpoints []server.Endpoint
	for _, ep := range c.Endpoints {
		logger.Infof( "setting up endpoint: basePath=%s,tokenProviderID=%s", ep.Config.BasePath, ep.Config.TokenProviderID )

		tokenProviderMatched := false
		var tokenProvider tokenprovider.TokenProvider

		logger.Debugf( "parsing token providers" )
		for _, tp := range c.TokenProviders {
			logger.Debugf( "looking at: tp.Id=%s", tp.Id )

			if tp.Id == ep.Config.TokenProviderID {
				logger.Debugf( "  found a match")

				tokenProvider, err = tp.Config.Open(logger)
				if err != nil {
					return fmt.Errorf( "failed to initialize token provider: %v", err)
				}

				tokenProviderMatched = true

				logger.Infof( "config tokenprovider: ID=%s, basePath=%s", ep.Config.TokenProviderID , ep.Config.BasePath )

				endpoints = append(endpoints, server.Endpoint{
					BasePath: ep.Config.BasePath,
					TokenProvider: tokenProvider,
				})

			} else {
				logger.Debugf( "  ...")
			}
		}

		if !tokenProviderMatched {
			return fmt.Errorf( "no token provider with tokenproviderid=%s configured", ep.Config.TokenProviderID )
		}
	}

	// explicitly convert to UTC.
	now := func() time.Time { return time.Now().UTC() }

	serverConfig := server.Config{
		Issuer:                 c.Issuer,
		Storage:                s,
		Endpoints:				endpoints,
		//TokenProvider:			tokenProviders,
		Logger:                 logger,
		Now:                    now,
		PrometheusRegistry:     prometheusRegistry,
	}
	if c.Expiry.SigningKeys != "" {
		signingKeys, err := time.ParseDuration(c.Expiry.SigningKeys)
		if err != nil {
			return fmt.Errorf("invalid config value %q for signing keys expiry: %v", c.Expiry.SigningKeys, err)
		}
		logger.Infof("config signing keys expire after: %v", signingKeys)
		serverConfig.RotateKeysAfter = signingKeys
	}
	if c.Expiry.IDTokens != "" {
		idTokens, err := time.ParseDuration(c.Expiry.IDTokens)
		if err != nil {
			return fmt.Errorf("invalid config value %q for id token expiry: %v", c.Expiry.IDTokens, err)
		}
		logger.Infof("config id tokens valid for: %v", idTokens)
		serverConfig.IDTokensValidFor = idTokens
	}

	serv, err := server.NewServer(context.Background(), serverConfig)
	if err != nil {
		return fmt.Errorf("failed to initialize server: %v", err)
	}

	telemetryServ := http.NewServeMux()
	telemetryServ.Handle("/metrics", promhttp.HandlerFor(prometheusRegistry, promhttp.HandlerOpts{}))

	errc := make(chan error, 3)
	if c.Telemetry.HTTP != "" {
		logger.Infof("listening (http/telemetry) on %s", c.Telemetry.HTTP)
		go func() {
			err := http.ListenAndServe(c.Telemetry.HTTP, telemetryServ)
			errc <- fmt.Errorf("listening on %s failed: %v", c.Telemetry.HTTP, err)
		}()
	}
	if c.HTTP.HTTP != "" {
		logger.Infof("listening (http) on %s", c.HTTP.HTTP)
		go func() {
			err := http.ListenAndServe(c.HTTP.HTTP, serv)
			errc <- fmt.Errorf("listening on %s failed: %v", c.HTTP.HTTP, err)
		}()
	}
	if c.HTTP.HTTPS != "" {
		logger.Infof("listening (https) on %s", c.HTTP.HTTPS)
		go func() {
			err := http.ListenAndServeTLS(c.HTTP.HTTPS, c.HTTP.TLSCert, c.HTTP.TLSKey, serv)
			errc <- fmt.Errorf("listening on %s failed: %v", c.HTTP.HTTPS, err)
		}()
	}


	return <-errc
}

var (
	logLevels  = []string{"debug", "info", "error"}
	logFormats = []string{"json", "text"}
)

type utcFormatter struct {
	f logrus.Formatter
}

func (f *utcFormatter) Format(e *logrus.Entry) ([]byte, error) {
	e.Time = e.Time.UTC()
	return f.f.Format(e)
}

func newLogger(level string, format string) (logrus.FieldLogger, error) {
	var logLevel logrus.Level
	switch strings.ToLower(level) {
	case "debug":
		logLevel = logrus.DebugLevel
	case "", "info":
		logLevel = logrus.InfoLevel
	case "error":
		logLevel = logrus.ErrorLevel
	default:
		return nil, fmt.Errorf("log level is not one of the supported values (%s): %s", strings.Join(logLevels, ", "), level)
	}

	var formatter utcFormatter
	switch strings.ToLower(format) {
	case "", "text":
		formatter.f = &logrus.TextFormatter{DisableColors: true}
	case "json":
		formatter.f = &logrus.JSONFormatter{}
	default:
		return nil, fmt.Errorf("log format is not one of the supported values (%s): %s", strings.Join(logFormats, ", "), format)
	}

	return &logrus.Logger{
		Out:       os.Stderr,
		Formatter: &formatter,
		Level:     logLevel,
	}, nil
}
